#include "mainwindow.h"
#include "sqleditor.h"
#include "databaseconnection.h"
#include "dataexplorer.h"
#include "dataexporter.h"
#include "dataimporter.h"
#include "tabmanager.h"
#include "tablemodel.h"
#include "connectionmanager.h"
#include "connectionwindow.h"
#include "importdialog.h"
#include "erdiagramview.h"
#include "databasediff.h"
#include "diffdialog.h"
#include "datagenerator.h"
#include "datagendialog.h"
#include "pluginmanager.h"
#include "dbtoolplugininterface.h"
#include "databasespecificmanager.h"
#include "databaseinfodialog.h"
#include "queryhistorymanager.h"
#include "queryhistorydialog.h"
#include "bookmarkmanager.h"
#include "bookmarkdialog.h"
#include <QApplication>
#include <QMenuBar>
#include <QToolBar>
#include <QStatusBar>
#include <QSplitter>
#include <QTreeWidget>
#include <QTableView>
#include <QHeaderView>
#include <QAction>
#include <QMessageBox>
#include <QInputDialog>
#include <QVBoxLayout>
#include <QWidget>
#include <QSqlQueryModel>
#include <QSqlQuery>
#include <QSqlError>
#include <QLineEdit>
#include <QFormLayout>
#include <QDialog>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTreeWidgetItem>
#include <QSqlRecord>
#include <QFileDialog>
#include <QProgressDialog>
#include <QComboBox>
#include <QLabel>
#include <QDialogButtonBox>
#include <QDockWidget>
#include <QTabWidget>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , tabManager(nullptr)
    , dbConnection(nullptr)
    , dataExplorer(nullptr)
    , dataExporter(nullptr)
    , dataImporter(nullptr)
    , connectionManager(new ConnectionManager(this))
    , erDiagramView(nullptr)
    , pluginManager(new PluginManager(this))
    , dbSpecificManager(new DatabaseSpecificManager(this))
    , m_queryHistoryManager(new QueryHistoryManager(this))
    , m_bookmarkManager(new BookmarkManager(this))
{
    setWindowTitle(tr("Database Tool"));
    resize(1024, 768);
    
    // 初始化查询历史管理器
    m_queryHistoryManager->initialize();
    
    // 初始化书签管理器
    m_bookmarkManager->initialize();
    
    createMenus();
    createToolBars();
    createStatusBar();
    setupCentralWidget();
    
    // 加载插件
    loadPlugins();
}

MainWindow::~MainWindow()
{
}

void MainWindow::createMenus()
{
    menuBar = new QMenuBar(this);
    setMenuBar(menuBar);
    
    // File menu
    fileMenu = menuBar->addMenu(tr("&File"));
    QAction *newTabAction = fileMenu->addAction(tr("&New Query Tab"));
    newTabAction->setShortcut(QKeySequence::AddTab);
    connect(newTabAction, &QAction::triggered, this, &MainWindow::addNewQueryTab);
    
    QAction *closeTabAction = fileMenu->addAction(tr("&Close Tab"));
    closeTabAction->setShortcut(QKeySequence::Close);
    connect(closeTabAction, &QAction::triggered, this, &MainWindow::closeCurrentTab);
    
    fileMenu->addSeparator();
    
    QAction *importAction = fileMenu->addAction(tr("&Import Data"));
    connect(importAction, &QAction::triggered, this, &MainWindow::importData);
    
    QAction *generateAction = fileMenu->addAction(tr("Generate &Data"));
    connect(generateAction, &QAction::triggered, this, &MainWindow::generateData);
    
    QAction *historyAction = fileMenu->addAction(tr("Query &History"));
    historyAction->setShortcut(QKeySequence("Ctrl+H"));
    connect(historyAction, &QAction::triggered, this, &MainWindow::showQueryHistory);
    
    QAction *bookmarkAction = fileMenu->addAction(tr("&Bookmarks"));
    bookmarkAction->setShortcut(QKeySequence("Ctrl+Shift+B"));
    connect(bookmarkAction, &QAction::triggered, this, &MainWindow::showBookmarks);
    
    QAction *exitAction = fileMenu->addAction(tr("E&xit"));
    connect(exitAction, &QAction::triggered, this, &MainWindow::close);
    
    // Database menu
    databaseMenu = menuBar->addMenu(tr("&Database"));
    QAction *connectAction = databaseMenu->addAction(tr("&Connect"));
    connect(connectAction, &QAction::triggered, this, &MainWindow::connectToDatabase);
    
    QAction *manageConnectionsAction = databaseMenu->addAction(tr("Manage Connections"));
    connect(manageConnectionsAction, &QAction::triggered, this, &MainWindow::manageConnections);
    
    QAction *disconnectAction = databaseMenu->addAction(tr("&Disconnect"));
    connect(disconnectAction, &QAction::triggered, this, &MainWindow::disconnectFromDatabase);
    
    QAction *refreshAction = databaseMenu->addAction(tr("&Refresh"));
    connect(refreshAction, &QAction::triggered, this, &MainWindow::refreshData);
    
    QAction *infoAction = databaseMenu->addAction(tr("Database &Info"));
    connect(infoAction, &QAction::triggered, this, &MainWindow::showDatabaseInfo);
    
    QAction *compareAction = databaseMenu->addAction(tr("Compare Databases"));
    connect(compareAction, &QAction::triggered, this, &MainWindow::compareDatabases);
    
    // View menu
    viewMenu = menuBar->addMenu(tr("&View"));
    QAction *erDiagramAction = viewMenu->addAction(tr("ER Diagram"));
    connect(erDiagramAction, &QAction::triggered, this, &MainWindow::showERDiagram);
    
    // Plugin menu
    m_pluginMenu = menuBar->addMenu(tr("&Plugins"));
    m_pluginMenu->setEnabled(false); // 初始时禁用，加载插件后启用
    
    // Tools menu
    toolsMenu = menuBar->addMenu(tr("&Tools"));
    QAction *exportTableAction = toolsMenu->addAction(tr("Export Table Data"));
    connect(exportTableAction, &QAction::triggered, this, &MainWindow::exportTableData);
    
    QAction *exportQueryAction = toolsMenu->addAction(tr("Export Query Results"));
    connect(exportQueryAction, &QAction::triggered, this, &MainWindow::exportQueryResults);
    
    // Edit menu
    QMenu *editMenu = menuBar->addMenu(tr("&Edit"));
    QAction *formatSqlAction = editMenu->addAction(tr("&Format SQL"));
    formatSqlAction->setShortcut(QKeySequence("Ctrl+Shift+F"));
    connect(formatSqlAction, &QAction::triggered, this, [this]() {
        if (tabManager) {
            SqlEditor *editor = tabManager->getCurrentSqlEditor();
            if (editor) {
                editor->formatSql();
            }
        }
    });
    
    // Help menu
    helpMenu = menuBar->addMenu(tr("&Help"));
    QAction *aboutAction = helpMenu->addAction(tr("&About"));
    connect(aboutAction, &QAction::triggered, [this]() {
        QMessageBox::about(this, tr("About Database Tool"),
                          tr("Database Tool - A C++ database management application"));
    });
}

void MainWindow::createToolBars()
{
    mainToolBar = addToolBar(tr("Main"));
    
    QAction *connectAction = mainToolBar->addAction(tr("Connect"));
    connect(connectAction, &QAction::triggered, this, &MainWindow::connectToDatabase);
    
    QAction *newTabAction = mainToolBar->addAction(tr("New Tab"));
    connect(newTabAction, &QAction::triggered, this, &MainWindow::addNewQueryTab);
    
    QAction *executeAction = mainToolBar->addAction(tr("Execute"));
    connect(executeAction, &QAction::triggered, this, [this]() {
        if (tabManager) {
            SqlEditor *editor = tabManager->getCurrentSqlEditor();
            if (editor) {
                QString sql = editor->getSqlText().trimmed();
                if (!sql.isEmpty()) {
                    executeQuery(sql);
                }
            }
        }
    });
    
    QAction *formatAction = mainToolBar->addAction(tr("Format"));
    connect(formatAction, &QAction::triggered, this, [this]() {
        if (tabManager) {
            SqlEditor *editor = tabManager->getCurrentSqlEditor();
            if (editor) {
                editor->formatSql();
            }
        }
    });
    
    QAction *historyAction = mainToolBar->addAction(tr("History"));
    connect(historyAction, &QAction::triggered, this, &MainWindow::showQueryHistory);
    
    QAction *bookmarkAction = mainToolBar->addAction(tr("Bookmarks"));
    connect(bookmarkAction, &QAction::triggered, this, &MainWindow::showBookmarks);
    
    QAction *refreshAction = mainToolBar->addAction(tr("Refresh"));
    connect(refreshAction, &QAction::triggered, this, &MainWindow::refreshData);
    
    QAction *erDiagramAction = mainToolBar->addAction(tr("ER Diagram"));
    connect(erDiagramAction, &QAction::triggered, this, &MainWindow::showERDiagram);
    
    QAction *compareAction = mainToolBar->addAction(tr("Compare"));
    connect(compareAction, &QAction::triggered, this, &MainWindow::compareDatabases);
    
    QAction *generateAction = mainToolBar->addAction(tr("Generate Data"));
    connect(generateAction, &QAction::triggered, this, &MainWindow::generateData);
    
    QAction *importAction = mainToolBar->addAction(tr("Import"));
    connect(importAction, &QAction::triggered, this, &MainWindow::importData);
    
    QAction *exportAction = mainToolBar->addAction(tr("Export"));
    connect(exportAction, &QAction::triggered, this, [this]() {
        // 简单导出，优先导出表数据，如果没有则导出查询结果
        exportTableData();
    });
    
    QAction *infoAction = mainToolBar->addAction(tr("DB Info"));
    connect(infoAction, &QAction::triggered, this, &MainWindow::showDatabaseInfo);
    
    // Plugin toolbar
    m_pluginToolBar = addToolBar(tr("Plugins"));
    m_pluginToolBar->setVisible(false); // 初始时隐藏，加载插件后显示
}

void MainWindow::createStatusBar()
{
    statusBar = new QStatusBar(this);
    setStatusBar(statusBar);
    statusBar->showMessage(tr("Ready"));
}

void MainWindow::setupCentralWidget()
{
    mainSplitter = new QSplitter(Qt::Horizontal, this);
    
    // Database explorer tree
    dbExplorerTree = new QTreeWidget(mainSplitter);
    dbExplorerTree->setHeaderLabel(tr("Database Explorer"));
    connect(dbExplorerTree, &QTreeWidget::itemDoubleClicked, this, [this](QTreeWidgetItem *item, int column) {
        if (item->parent() != nullptr && item->parent()->text(0) == tr("Tables")) {
            loadTable(item->text(0));
        }
    });
    
    // 右侧区域：Tab管理器和数据浏览器的垂直分割
    QSplitter *rightSplitter = new QSplitter(Qt::Vertical, mainSplitter);
    
    // Tab管理器
    tabManager = new TabManager(rightSplitter);
    connect(tabManager, &TabManager::executeQuery, this, &MainWindow::executeQuery);
    
    // Data explorer
    dataExplorer = new DataExplorer(rightSplitter);
    connect(dataExplorer, &DataExplorer::tableLoaded, this, [this](const QString &tableName) {
        statusBar->showMessage(tr("Loaded table: %1").arg(tableName));
    });
    
    mainSplitter->setStretchFactor(0, 1);
    mainSplitter->setStretchFactor(1, 3);
    
    setCentralWidget(mainSplitter);
}

void MainWindow::setupDatabaseExplorer()
{
    if (!currentDatabase.isOpen()) {
        return;
    }
    
    dbExplorerTree->clear();
    
    // 添加数据库连接项
    QTreeWidgetItem *connectionItem = new QTreeWidgetItem(dbExplorerTree);
    connectionItem->setText(0, tr("Connected Database"));
    connectionItem->setExpanded(true);
    
    // 添加表项
    QTreeWidgetItem *tablesItem = new QTreeWidgetItem(connectionItem);
    tablesItem->setText(0, tr("Tables"));
    tablesItem->setExpanded(true);
    
    // 查询并添加所有表
    QSqlQuery query(currentDatabase);
    query.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name");
    if (query.exec()) {
        while (query.next()) {
            QTreeWidgetItem *tableItem = new QTreeWidgetItem(tablesItem);
            tableItem->setText(0, query.value(0).toString());
        }
    }
    
    // 如果不是SQLite，使用标准方式查询表
    if (!query.isActive() || query.size() == 0) {
        QStringList tables = currentDatabase.tables();
        for (const QString &table : tables) {
            QTreeWidgetItem *tableItem = new QTreeWidgetItem(tablesItem);
            tableItem->setText(0, table);
        }
    }
}

void MainWindow::connectToDatabase()
{
    showConnectionDialog();
    
    // 更新SQL编辑器的自动补全功能
    if (tabManager) {
        tabManager->updateAutoCompletion();
    }
}

void MainWindow::showConnectionDialog()
{
    ConnectionWindow connWindow(connectionManager, this);
    if (connWindow.exec() == QDialog::Accepted) {
        QString connectionName = connWindow.getSelectedConnection();
        if (!connectionName.isEmpty()) {
            QSqlDatabase db = connectionManager->createDatabaseConnection(connectionName);
            if (db.open()) {
                statusBar->showMessage(tr("Connected to database: %1").arg(connectionName));
                currentDatabase = db;
                setupDatabaseExplorer();
                
                // 初始化数据导出器
                if (!dataExporter) {
                    dataExporter = new DataExporter(this);
                }
                
                // 初始化数据导入器
                if (!dataImporter) {
                    dataImporter = new DataImporter(this);
                }
                
                // 更新数据库特定功能管理器
                dbSpecificManager->setDatabase(currentDatabase);
                
                // 更新TabManager中的数据库连接
                if (tabManager) {
                    tabManager->setDatabase(currentDatabase);
                }
                
                // 更新数据浏览器中的数据库连接
                if (dataExplorer) {
                    dataExplorer->setDatabase(currentDatabase);
                }
                
                // 通知插件数据库已连接
                QList<DBToolPluginInterface*> dbPlugins = pluginManager->getPlugins<DBToolPluginInterface>();
                for (DBToolPluginInterface *plugin : dbPlugins) {
                    plugin->setDatabase(currentDatabase);
                }
            } else {
                QMessageBox::warning(this, tr("Connection Error"), 
                                    tr("Failed to connect to database: %1")
                                    .arg(db.lastError().text()));
            }
        }
    }
}

void MainWindow::manageConnections()
{
    ConnectionWindow connWindow(connectionManager, this);
    connWindow.exec();
}

void MainWindow::disconnectFromDatabase()
{
    if (currentDatabase.isOpen()) {
        QString connectionName = currentDatabase.connectionName();
        currentDatabase.close();
        QSqlDatabase::removeDatabase(connectionName);
        currentDatabase = QSqlDatabase();
        statusBar->showMessage(tr("Disconnected from database"));
        dbExplorerTree->clear();
        
        // 更新SQL编辑器的自动补全功能
        if (tabManager) {
            tabManager->updateAutoCompletion();
        }
        
        // 通知插件数据库已断开连接
        QList<DBToolPluginInterface*> dbPlugins = pluginManager->getPlugins<DBToolPluginInterface>();
        for (DBToolPluginInterface *plugin : dbPlugins) {
            plugin->setDatabase(currentDatabase);
        }
    }
}

void MainWindow::executeQuery(const QString &query)
{
    if (!currentDatabase.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("Not connected to a database"));
        return;
    }
    
    // 添加查询到历史记录
    m_queryHistoryManager->addQuery(query, currentDatabase.databaseName());
    
    QSqlQueryModel *model = new QSqlQueryModel(this);
    model->setQuery(query, currentDatabase);
    
    showQueryResults(model);
    
    // 通知当前的SqlEditor查询已完成
    if (tabManager) {
        SqlEditor *editor = tabManager->getCurrentSqlEditor();
        if (editor) {
            editor->onQueryExecuted(model);
        }
    }
    
    // 通知插件执行了查询
    QVariantMap params;
    params["query"] = query;
    QList<DBToolPluginInterface*> dbPlugins = pluginManager->getPlugins<DBToolPluginInterface>();
    for (DBToolPluginInterface *plugin : dbPlugins) {
        plugin->handleEvent("queryExecuted", params);
    }
}

void MainWindow::showQueryResults(QSqlQueryModel *model)
{
    // 在当前活动的SqlEditor中显示查询结果
    if (tabManager) {
        SqlEditor *editor = tabManager->getCurrentSqlEditor();
        if (editor) {
            editor->onQueryExecuted(model);
        }
    }
}

void MainWindow::loadTable(const QString &tableName)
{
    if (!currentDatabase.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("No database connection"));
        return;
    }
    
    dataExplorer->setDatabase(currentDatabase);
    dataExplorer->loadTable(tableName);
    
    // 通知插件加载了表
    QVariantMap params;
    params["tableName"] = tableName;
    QList<DBToolPluginInterface*> dbPlugins = pluginManager->getPlugins<DBToolPluginInterface>();
    for (DBToolPluginInterface *plugin : dbPlugins) {
        plugin->handleEvent("tableLoaded", params);
    }
}

void MainWindow::refreshData()
{
    if (dataExplorer) {
        dataExplorer->refresh();
    }
    
    // 通知插件刷新了数据
    QList<DBToolPluginInterface*> dbPlugins = pluginManager->getPlugins<DBToolPluginInterface>();
    for (DBToolPluginInterface *plugin : dbPlugins) {
        plugin->handleEvent("dataRefreshed", QVariantMap());
    }
}

void MainWindow::exportTableData()
{
    // 检查是否有可导出的表数据
    TableModel *tableModel = nullptr;
    if (dataExplorer) {
        tableModel = dataExplorer->getModel();
        if (tableModel) {
            showExportDialog(tableModel, nullptr);
        } else {
            QMessageBox::information(this, tr("Export"), tr("No table data available for export"));
        }
    } else {
        QMessageBox::information(this, tr("Export"), tr("No table data available for export"));
    }
}

void MainWindow::exportQueryResults()
{
    // 导出查询结果
    QSqlQueryModel *queryModel = nullptr;
    if (tabManager) {
        SqlEditor *editor = tabManager->getCurrentSqlEditor();
        if (editor) {
            queryModel = editor->getQueryModel();
            if (queryModel) {
                showExportDialog(nullptr, queryModel);
            } else {
                QMessageBox::information(this, tr("Export"), tr("No query results available for export"));
            }
        }
    } else {
        QMessageBox::information(this, tr("Export"), tr("No query results available for export"));
    }
}

void MainWindow::showExportDialog(QSqlTableModel *tableModel, QSqlQueryModel *queryModel)
{
    if (!dataExporter) {
        QMessageBox::warning(this, tr("Error"), tr("Data exporter not available"));
        return;
    }
    
    QDialog dialog(this);
    dialog.setWindowTitle(tr("Export Data"));
    
    QFormLayout *formLayout = new QFormLayout;
    
    QLineEdit *fileEdit = new QLineEdit;
    QPushButton *browseButton = new QPushButton(tr("Browse..."));
    connect(browseButton, &QPushButton::clicked, [&fileEdit, this]() {
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save Export File"), 
                                                       QString(), 
                                                       tr("CSV Files (*.csv);;JSON Files (*.json);;XML Files (*.xml);;SQL Files (*.sql);;All Files (*)"));
        if (!fileName.isEmpty()) {
            fileEdit->setText(fileName);
        }
    });
    
    QHBoxLayout *fileLayout = new QHBoxLayout;
    fileLayout->addWidget(fileEdit);
    fileLayout->addWidget(browseButton);
    
    QComboBox *formatCombo = new QComboBox;
    formatCombo->addItem(tr("CSV"), DataExporter::CSV);
    formatCombo->addItem(tr("JSON"), DataExporter::JSON);
    formatCombo->addItem(tr("XML"), DataExporter::XML);
    formatCombo->addItem(tr("SQL"), DataExporter::SQL);
    
    formLayout->addRow(tr("File:"), fileLayout);
    formLayout->addRow(tr("Format:"), formatCombo);
    
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(formLayout);
    mainLayout->addWidget(buttonBox);
    
    dialog.setLayout(mainLayout);
    
    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    
    if (dialog.exec() == QDialog::Accepted) {
        QString fileName = fileEdit->text();
        if (fileName.isEmpty()) {
            QMessageBox::warning(this, tr("Error"), tr("Please specify a file name"));
            return;
        }
        
        DataExporter::ExportFormat format = static_cast<DataExporter::ExportFormat>(formatCombo->currentData().toInt());
        
        // 创建进度对话框
        QProgressDialog progressDialog(tr("Exporting data..."), tr("Cancel"), 0, 100, this);
        progressDialog.setWindowModality(Qt::WindowModal);
        progressDialog.setAutoClose(false);
        progressDialog.setAutoReset(false);
        
        connect(dataExporter, &DataExporter::exportProgress, &progressDialog, &QProgressDialog::setValue);
        connect(dataExporter, &DataExporter::exportFinished, [&progressDialog](const QString &message) {
            progressDialog.close();
            QMessageBox::information(nullptr, tr("Export Finished"), message);
        });
        connect(dataExporter, &DataExporter::exportError, [&progressDialog](const QString &error) {
            progressDialog.close();
            QMessageBox::warning(nullptr, tr("Export Error"), error);
        });
        
        // 执行导出
        if (tableModel) {
            dataExporter->exportTable(tableModel, fileName, format);
        } else if (queryModel) {
            dataExporter->exportQueryResults(queryModel, fileName, format);
        } else {
            QMessageBox::information(this, tr("Export"), tr("No data to export"));
        }
    }
}

void MainWindow::importData()
{
    if (!currentDatabase.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("Not connected to a database"));
        return;
    }
    
    showImportDialog();
}

void MainWindow::showImportDialog()
{
    if (!dataImporter) {
        dataImporter = new DataImporter(this);
    }
    
    ImportDialog dialog(currentDatabase, this);
    if (dialog.exec() == QDialog::Accepted) {
        QString fileName = dialog.getFileName();
        QString tableName = dialog.getTableName();
        int format = dialog.getFormat();
        
        // 创建进度对话框
        QProgressDialog progressDialog(tr("Importing data..."), tr("Cancel"), 0, 100, this);
        progressDialog.setWindowModality(Qt::WindowModal);
        progressDialog.setAutoClose(false);
        progressDialog.setAutoReset(false);
        
        connect(dataImporter, &DataImporter::importProgress, &progressDialog, &QProgressDialog::setValue);
        connect(dataImporter, &DataImporter::importFinished, [&progressDialog](const QString &message) {
            progressDialog.close();
            QMessageBox::information(nullptr, tr("Import Finished"), message);
        });
        connect(dataImporter, &DataImporter::importError, [&progressDialog](const QString &error) {
            progressDialog.close();
            QMessageBox::warning(nullptr, tr("Import Error"), error);
        });
        
        // 执行导入
        DataImporter::ImportFormat importFormat = static_cast<DataImporter::ImportFormat>(format);
        dataImporter->importFile(fileName, tableName, importFormat, currentDatabase);
    }
}

void MainWindow::showERDiagram()
{
    if (!currentDatabase.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("Not connected to a database"));
        return;
    }
    
    // 创建ER图视图
    if (!erDiagramView) {
        erDiagramView = new ERDiagramView();
    }
    
    erDiagramView->setDatabase(currentDatabase);
    erDiagramView->refreshDiagram();
    
    // 创建停靠窗口显示ER图
    QDockWidget *dock = new QDockWidget(tr("ER Diagram"), this);
    dock->setWidget(erDiagramView);
    dock->setAllowedAreas(Qt::AllDockWidgetAreas);
    
    addDockWidget(Qt::RightDockWidgetArea, dock);
    
    // 如果停靠窗口已经存在，则显示它
    dock->show();
    dock->raise();
    dock->setFocus();
}

void MainWindow::compareDatabases()
{
    if (!currentDatabase.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("Not connected to a database"));
        return;
    }
    
    showDiffDialog();
}

void MainWindow::showDiffDialog()
{
    DiffDialog dialog(currentDatabase, this);
    dialog.exec();
}

void MainWindow::generateData()
{
    if (!currentDatabase.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("Not connected to a database"));
        return;
    }
    
    showDataGenDialog();
}

void MainWindow::showDataGenDialog()
{
    DataGenDialog dialog(currentDatabase, this);
    dialog.exec();
}

void MainWindow::showDatabaseInfo()
{
    if (!currentDatabase.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("Not connected to a database"));
        return;
    }
    
    showDatabaseInfoDialog();
}

void MainWindow::showDatabaseInfoDialog()
{
    DatabaseInfoDialog dialog(currentDatabase, this);
    dialog.exec();
}

void MainWindow::showQueryHistory()
{
    showQueryHistoryDialog();
}

void MainWindow::showQueryHistoryDialog()
{
    QueryHistoryDialog dialog(m_queryHistoryManager, this);
    connect(&dialog, &QueryHistoryDialog::querySelected, this, [this](const QString &query) {
        if (tabManager) {
            SqlEditor *editor = tabManager->getCurrentSqlEditor();
            if (editor) {
                editor->setSqlText(query);
            }
        }
    });
    
    dialog.exec();
}

void MainWindow::showBookmarks()
{
    showBookmarkDialog();
}

void MainWindow::showBookmarkDialog()
{
    QString currentQuery;
    if (tabManager) {
        SqlEditor *editor = tabManager->getCurrentSqlEditor();
        if (editor) {
            currentQuery = editor->getSqlText();
        }
    }
    
    BookmarkDialog dialog(m_bookmarkManager, currentQuery, currentDatabase.databaseName(), this);
    connect(&dialog, &BookmarkDialog::querySelected, this, [this](const QString &query) {
        if (tabManager) {
            SqlEditor *editor = tabManager->getCurrentSqlEditor();
            if (editor) {
                editor->setSqlText(query);
            }
        }
    });
    
    dialog.exec();
}

void MainWindow::loadPlugins()
{
    pluginManager->loadPlugins();
    
    // 获取所有数据库工具插件
    QList<DBToolPluginInterface*> dbPlugins = pluginManager->getPlugins<DBToolPluginInterface>();
    
    if (!dbPlugins.isEmpty()) {
        // 启用插件菜单和工具栏
        m_pluginMenu->setEnabled(true);
        m_pluginToolBar->setVisible(true);
        
        // 初始化插件
        for (DBToolPluginInterface *plugin : dbPlugins) {
            // 设置主窗口引用
            plugin->setMainWindow(this);
            
            // 设置当前数据库（如果已连接）
            if (currentDatabase.isOpen()) {
                plugin->setDatabase(currentDatabase);
            }
            
            // 初始化插件
            if (plugin->initialize()) {
                // 添加菜单项
                plugin->addMenuItems(m_pluginMenu);
                
                // 添加工具栏项
                plugin->addToolBarItems(m_pluginToolBar);
                
                statusBar->showMessage(tr("Loaded plugin: %1").arg(plugin->name()));
            } else {
                qWarning() << "Failed to initialize plugin:" << plugin->name();
            }
        }
    }
}

void MainWindow::addNewQueryTab()
{
    if (tabManager) {
        tabManager->addQueryTab();
    }
}

void MainWindow::closeCurrentTab()
{
    if (tabManager) {
        // 确保至少保留一个标签
        if (tabManager->count() > 1) {
            tabManager->removeTab(tabManager->currentIndex());
        } else {
            QMessageBox::information(this, tr("Close Tab"), tr("Cannot close the last tab"));
        }
    }
}